package cn.hls.web.controller.dict;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hls.entity.Org;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.Msg;
import cn.hls.entity.vo.PageInfo;
import cn.hls.service.OrgService;
import cn.hls.web.controller.base.BaseController;

@Controller
@RequestMapping("/org")
public class OrgController extends BaseController<Org> {
	@Resource(name = "orgService")
	private OrgService orgService;
	@RequestMapping("/add")
	@ResponseBody
	public Msg add(Org entity) throws Exception {
		Org org = orgService.findOrg(entity);
		if (org != null) {// 对象存在
			msg.setStatus(201);
			msg.setInfo("单位(机构)名称或代码已经存在");
		} else {
			boolean flag = orgService.add(entity);
			if (!flag) {
				msg.setStatus(202);
				msg.setInfo("操作失败");
			}else{
				msg.setInfo("操作成功");
				msg.setStatus(200);
				msg.setSuccess(true);
			}
		}
		return msg;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Msg update(Org entity) throws Exception {
		if (entity.getParent().getId() == null)
			entity.setParent(null);
		else
			entity.setParent(orgService.find(entity.getParent().getId()));
		if (entity.getUpdateTime() == null) {
			entity.setUpdateTime(new Date());
		}
		boolean flag = orgService.update(entity);
		if (!flag) {
			msg.setStatus(201);
			msg.setInfo("操作失败");
		}else{
			msg.setInfo("操作成功");
			msg.setStatus(200);
			msg.setSuccess(true);
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping("/del")
	public Msg del(Long id) throws Exception {
		String result = orgService.deleteOrg(id);
		if (!result.equalsIgnoreCase("ok")) {
			msg.setStatus(201);
			msg.setInfo(result);
		}else{
			msg.setInfo("操作成功");
			msg.setStatus(200);
			msg.setSuccess(true);
		}
		return msg;
	}

	// 排序
	@ResponseBody
	@RequestMapping("/sort")
	public Msg sort(String ids) throws Exception {
		try {
			orgService.updateOrgSort(ids);
			return msg;
		} catch (Exception e) {
			throw e;
		}
	}

	@RequestMapping("/view")
	public String view() {
		return "dict/org";
	}

	@RequestMapping("/list")
	@ResponseBody
	public PageInfo<Org> list(Org entity, PageInfo<Org> page) throws Exception {
		return orgService.loadOrgInfo(entity, page);
	}

	@ResponseBody
	@RequestMapping("/tree")
	public List<ExtTree> tree(Org entity, Long nodeId) throws Exception {
		return orgService.loadChildOrgInfo(entity, nodeId == null
				|| nodeId == 0 ? null : nodeId);
	}

	 
}
